<template>
  <div class="music-progress" @touchstart="touchStart" @touchend="touchEnd" @touchmove="touchMove">
    <div class="progress-bar">
      <span :style="{width:currentProgress+'%'}" class="progress-current"/>
      <div :style="{left:currentProgress+'%',marginLeft:'-'+marginLeft+'px'}" class="progress-info" ref="pivot">
        <slot name="pivot">
          <div class="de soft white" style="width: 10px;height: 10px;border:1px solid #999"></div>
        </slot>
      </div>
    </div>
  </div>
</template>

<script setup>

import {toRefs, defineProps, watch, ref, onMounted} from "vue";

let emit = defineEmits(["changeProgress"]);


let currentProgress = ref(0);
let currentProgressFlag = ref(true);
let propsDef = defineProps({
  progress: {
    type: Number,
    default: 0
  },
  progressColor: {
    type: String,
    default: "red"
  }
});
let props = toRefs(propsDef);


let pivot = ref(null);
let marginLeft = ref(0);

onMounted(() => {
  watch(props.progress, (progress) => {
    if (currentProgressFlag.value && (progress >= 0 || progress <= 100)) {
      currentProgress.value = progress;
    }
    let left = pivot.value?.clientWidth;
    marginLeft.value = left / 2;
  }, {
    immediate: true
  });
});


let startPosition = {
  x: 0
}
let isMove = false;

function touchStart(event) {
  event = event.touches[0];
  currentProgressFlag.value = false;
  startPosition.x = event.clientX;
  isMove = false;
}

function touchEnd(event) {
  let bounding = event.target.getBoundingClientRect();
  // 最小值
  let min = startPosition.x - bounding.x;
  // 最大值
  let max = (bounding.width);
  if (!isMove) {
    currentProgress.value = (min / max) * 100;
  }
  console.log(min / max * 100);
  event = event.changedTouches[0];
  currentProgressFlag.value = true;
  emit("changeProgress", currentProgress.value);
}

function touchMove(event) {
  event = event.touches[0];
  let seed = 0.6;
  if (event.clientX > startPosition.x) {
    if (currentProgress.value + seed > 100) {
      currentProgress.value = 100
    } else {
      currentProgress.value += seed;
    }
  } else {
    if (currentProgress.value - seed < 0) {
      currentProgress.value = 0
    } else {
      currentProgress.value -= seed;
    }
  }
  setTimeout(() => {
    startPosition.x = event.clientX;
    isMove = true;
  });
}
</script>

<style lang="scss" scoped>
.music-progress {
  display: flex;
  align-items: center;
  height: 1rem;

  .progress-bar {
    display: flex;
    align-items: center;
    position: relative;
    width: 100%;
    height: 4px;
    background: #ccc;

    .progress-current {
      display: block;
      height: 100%;
      background: v-bind(progressColor);
    }

    .progress-info {
      display: block;
      position: absolute;
      width: auto;
      height: auto;
    }
  }

}
</style>